<?php
/**
 * PC端用户登录
 * User: dxk <duxiaokong@sina.com>
 * Date: 2023/3/25 17:28
 */

namespace App\OpenApi\AdminApi\Passport;

use App\Library\Service\SMSSend;
use App\Library\Service\Verify;
use App\Model\Core\Admin\AdminUserModel;
use App\Service\Auth\AdminAuthService;
use App\Service\OpenApi\AdminApi\AppAuthService;
use App\Service\OpenApi\AdminApi\OpenBaseApi;

class LoginApi extends OpenBaseApi
{
    /**
     * 用户名/手机号 密码登录
     * @return array
     */
    public function index(): array
    {
        $username = trim($this->input('username'));
        $password = trim($this->input('password'));
        $device_id = trim($this->input('device_id'));
        if (empty($username)) {
            return alert_info(1, '用户名为空');
        }
        $user_info = AdminUserModel::getInstance()->getUserByMobile($username);
        if (empty($user_info)) {
            return alert_info(1, '用户不存在');
        }
        $user_id = $user_info['user_id'];
        if (!\Hash::check($password, $user_info['password'])) {
            AdminUserModel::getInstance()->updateOne($user_id,
                [
                    'error_login_times' => $user_info['error_login_times'] + 1,
                    'error_login_at' => date('Y-m-d H:i:s'),
                    'last_login_ip' => easy_ip()
                ]);
            return alert_info(1, '密码错误');
        }
        $res = AdminAuthService::login($user_id);
        if ($res['code'] !== 0) {
            return $res;
        }
        unset($user_info['password']);
        $auth_res = (new AppAuthService($this->app_key))->auth($user_id, ['device_id' => $device_id]);
        if ($auth_res['code'] !== 0) {
            return alert_info(1, '用户授权失败,' . $auth_res['msg']);
        }
        return alert_info(0, '登录成功', [
            'access_token' => $auth_res['data']['access_token'],
            'user_info' => $user_info,
            'first_login' => $user_info['pre_login_at'] == '0000-00-00 00:00:00' ? 1 : 0
        ]);
    }

    /**
     * 找回密码发送短信验证码
     * @return array
     */
    public function sendCode()
    {
        $mobile = trim($this->input('mobile'));
        if (!Verify::isMobile($mobile)) {
            return alert_info(1, '请输入正确的手机号');
        }
        $user = AdminUserModel::getInstance()->getUserByMobile($mobile);
        if (empty($user)) {
            return alert_info(1, '账号不存在');
        }
        $SMS = new SMSSend();
        $res = $SMS->sendCaptcha($mobile, config('sys.aliyun.sms_tpl_reset_password'));
        if (!isset($res['code']) || $res['code'] !== 0) {
            return $res;
        }
        $data = [
            'code' => $res['data']['captcha']
        ];
        return alert_info(0, '短信发送成功', $data);
    }

    /**
     * 重置密码
     * @return array
     */
    public function resetPassword()
    {
        $mobile = trim($this->input('mobile'));
        if (!Verify::isMobile($mobile)) {
            return alert_info(1, '请输入正确的手机号');
        }
        $vcode = trim($this->input('yzm'));
        //校验短信验证码
        $SMS = new SMSSend();
        $res = $SMS->verifyCaptcha($mobile, config('sys.aliyun.sms_tpl_reset_password'), $vcode);
        if (!$res) {
            return alert_info(1, '手机验证码错误');
        }
        $AdminUserModel = AdminUserModel::getInstance();
        $user = $AdminUserModel->getUserByMobile($mobile);
        if (empty($user)) {
            return alert_info(1, '账号不存在');
        }
        $user_id = $user['user_id'];
        $newpw = trim($this->input('newpw'));
        if (empty($newpw)) {
            return alert_info(1, '新密码不能为空');
        }
        $newpw2 = trim($this->input('newpw2'));
        if (empty($newpw2)) {
            return alert_info(1, '确认新密不能为空');
        }
        if ($newpw !== $newpw2) {
            return alert_info(1, '两次输入密码不一致');
        }
        //修改密码
        $conn = $AdminUserModel->getConnection();
        $conn->beginTransaction();
        $user = $AdminUserModel->getOne($user_id, true);
        if (empty($user)) {
            $conn->rollBack();
            return alert_info(1, '用户获取失败');
        }
        $res = $AdminUserModel->updateOne($user_id,
            [
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => '找回密码',
                'password' => bcrypt($newpw)
            ]);
        if ($res === false) {
            $conn->rollBack();
            return alert_info(1, '密码重置失败');
        }
        $conn->commit();
        (new AppAuthService($this->app_key))->cancelAuth($this->token);
        return alert_info(0, '操作成功');
    }

    /**
     * @return array
     */
    public function logout(): array
    {
        (new AppAuthService($this->app_key))->cancelAuth($this->token);
        return alert_info(0, '退出成功');
    }
}
